<?php
namespace app\api\controller\basemanage;
use app\api\controller\common\ApiBase;
use think\Controller; // den
use think\Db;
// Controller  ApiBase （dengl）
class Member extends ApiBase
{
    /**
     *
     * @return \think\response\Json|void
     *  comppub
     *
     */

    public function getList(){
        $page = $this->request->param('pageIndex');
        $mobile = $this->request->param('mobile');
        $name = $this->request->param('name');
        $page = max(1,intval($page));
        $pageSize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $param=" and u.is_delete=0";
        if (!empty($mobile)) {
            $param.=" and u.mobile like '%$mobile%' ";
        }
        if (!empty($name)) {
            $param.=" and u.nickname like '%$name%' ";
        }
        $sql2="SELECT u.*,v.id as vip_id,v.card_id,v.card_end_time,v.card_start_time,c.title as card_title,c.wash_protect_num,c.card_price,r.record_amount,a.maintain_amount_t,inc.integral_num_cz,inx.integral_num_xf FROM crm_member_user AS u ";
        $sql2.=" LEFT JOIN crm_member_vip AS v ON v.member_id=u.id AND v.is_delete=0";
        $sql2.=" LEFT JOIN crm_cards AS c ON c.id=v.card_id ";
        $sql2.=" LEFT JOIN (SELECT SUM(amount) as record_amount,member_id FROM crm_member_recharge WHERE is_delete=0 GROUP BY member_id) AS r ON r.member_id=u.id  ";
        $sql2.=" LEFT JOIN (SELECT SUM(integral_num) as integral_num_cz,member_id FROM crm_member_integral WHERE integral_type=1 GROUP BY member_id) AS inc ON inc.member_id=u.id  ";
        $sql2.=" LEFT JOIN (SELECT SUM(integral_num) as integral_num_xf,member_id FROM crm_member_integral WHERE integral_type=2 GROUP BY member_id) AS inx ON inx.member_id=u.id  ";
        $sql2.=" LEFT JOIN (SELECT SUM(monetary) as maintain_amount_t,member_id FROM crm_member_record WHERE is_delete=0 AND katz_or_amount=2 GROUP BY member_id) AS a ON a.member_id=u.id  ";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by u.id desc";
        $total1=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pageSize.",$pageSize";
        $list=Db::query($sql2);
        foreach ($list as &$v){
            $v['vip_status']=$v['vip_id'] && $v['card_end_time']>=time()?1:0;
            $v['amount_total']=$v['record_amount']-$v['maintain_amount_t'];
            $v['integral_total']=$v['integral_num_cz']-$v['integral_num_xf'];
        }
        $total=count($total1); //st
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total]]);
    }


    /**
     * 添加
     * @return \think\response\Json|void
     *  zs_question       zs_question_option
     *  zs_question_type
     */
    public function add(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $mobile = isset($post['mobile']) && $post['mobile'] != '' ? $post['mobile'] : null;
                if(!$mobile){
                    return json(array('code' => '0', 'msg' => '电话号码误'));
                }
                $submit_type = isset($post['submit_type']) && $post['submit_type'] != '' ? $post['submit_type'] : 0;
                if($submit_type == 0){
                    return json(array('code' => '0', 'msg' => '参数类型错误'));
                }
                $rUser=db('member_user')->where(['is_delete'=>0,'mobile'=>$mobile])->find();
                //会员卡信息提交
                $server_id=isset($post['serve_id']) && $post['serve_id'] != '' ? $post['serve_id'] : 0;
                $amount=isset($post['amount']) && $post['amount'] != '' ? $post['amount'] : 0;
                $stored_id=isset($post['stored_id']) && $post['stored_id'] != '' ? $post['stored_id'] : null;
                $nickname=isset($post['nickname']) && $post['nickname'] != '' ? $post['nickname'] : null;
                $integral_num=isset($post['integral_num']) && $post['integral_num'] != '' ? $post['integral_num'] : 0;
                $cRes=null;
                $rRes=null;
                $serveRes=null;
                $wash_protect_num=0;
                if($submit_type == 1){
                    $card_id=isset($post['card_id']) && $post['card_id'] != '' ? $post['card_id'] : 0;
                    $cRes=db('cards')->where(['is_delete'=>0,'id'=>$card_id])->find();
                    if(!$cRes){
                        return json(array('code' => '0', 'msg' => '会员卡信息错误'));
                    }
                    if($rUser && $rUser['id']){
                        $isVip=db('member_vip')->where(['is_delete'=>0,'member_id'=>$rUser['id'],'card_end_time'=>array('egt',time())])->find();
                        if($isVip){
                            return json(array('code' => '0', 'msg' => '此客户已是会员客户，不可重复添加!'));
                        }
                    }
                }else if($submit_type == 2){
//                    if(!$amount){
//                        return json(array('code' => '0', 'msg' => '参数信息错误'));
//                    }
                }else if($submit_type == 3){
                    $serveRes=db('cards_server')->where(['is_delete'=>0,'id'=>$server_id])->find();
                    if(!$serveRes){
                        return json(array('code' => '0', 'msg' => '服务卡信息错误'));
                    }
                }else if($submit_type == 4){
                    if(!$integral_num){
                        return json(array('code' => '0', 'msg' => '积分信息错误'));
                    }
                }

                $remember_id=null;
                if(!$rUser){
                    $userDate['update_time']=time();
                    $userDate['create_time']=time();
                    $userDate['nickname']=$nickname;
                    $userDate['mobile']=$mobile;
                    $remember_id=db('member_user')->lock(true)->insertGetId($userDate);
                    if(false === $remember_id){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,会员信息添加失败'));
                    }
                    $wash_protect_num=0;
                }else{
                    $rememberUp=db('member_user')->where(['id'=>$rUser['id']])->update(['nickname'=>$nickname,'update_time'=>time()]);
                    if(false === $rememberUp){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,会员信息更新失败'));
                    }
                    $remember_id=$rUser['id'];
                    $wash_protect_num=$rUser['wash_protect_num_total'];
                }
                $nowDate=date('Y-m-d H:i:s',time());
                $card_start_time=time();
                if($submit_type == 1){
                    $card_year=$cRes['card_year'];
                    $card_end_time=strtotime("+".$card_year."years",strtotime($nowDate));
                    $vipDate['update_time']=time();
                    $vipDate['card_start_time']=$card_start_time;
                    $vipDate['card_end_time']=$card_end_time;
                    $vipDate['card_id']=$cRes['id'];
                    $vip_id=db('member_vip')->where(['is_delete'=>0,'member_id'=>$remember_id])->find();
                    if($vip_id && $vip_id['id']){
                        $vRes=db('member_vip')->lock(true)->where(['id'=>$vip_id['id']])->update($vipDate);
                        if(false === $vRes){
                            Db::rollback();
                            return json(array('code' => '0', 'msg' => '操作失败,会员卡信息添加失败'));
                        }
                    }else{
                        $vipDate['create_time']=time();
                        $vipDate['member_id']=$remember_id;
                        $vRes=db('member_vip')->lock(true)->insert($vipDate);
                        if(false === $vRes){
                            Db::rollback();
                            return json(array('code' => '0', 'msg' => '操作失败,会员卡信息添加失败'));
                        }
                    }
                    $user_integral_num=$wash_protect_num+$cRes['wash_protect_num'];
                    $cardNumRes=db('member_user')->where(['id'=>$remember_id])->update(['wash_protect_num_total'=>$user_integral_num]);
                    if($cardNumRes === false){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,洗护次数添加失败'));
                    }
                }else if($submit_type == 2){
                    if($stored_id || $amount>0){
                        $rechargeDate['update_time']=time();
                        $rechargeDate['create_time']=time();
                        $rechargeDate['amount']=$amount;
                        $rechargeDate['stored_id']=$stored_id;
                        $rechargeDate['member_id']=$remember_id;
                        $ruRes=db('member_recharge')->lock(true)->insert($rechargeDate);
                        if(false === $ruRes){
                            Db::rollback();
                            return json(array('code' => '0', 'msg' => '操作失败,储值卡添加失败'));
                        }
                    }
                    $washTotal=isset($post['wash_protect_num_total']) && $post['wash_protect_num_total'] != '' ? $post['wash_protect_num_total'] : 0;
                    if($washTotal){
                        $user_integral_num=$wash_protect_num+$washTotal;
                        $cardNumRes=db('member_user')->where(['id'=>$remember_id])->update(['wash_protect_num_total'=>$user_integral_num]);
                        if($cardNumRes === false){
                            Db::rollback();
                            return json(array('code' => '0', 'msg' => '操作失败,洗护次数添加失败'));
                        }
                    }
                }else if($submit_type == 3){
                    $server_year=$serveRes['card_year'];
                    $card_end_time=strtotime("+".$server_year."years",strtotime($nowDate));
                    $serverDate['update_time']=time();
                    $serverDate['create_time']=time();
                    $serverDate['card_start_time']=$card_start_time;
                    $serverDate['card_end_time']=$card_end_time;
                    $serverDate['serve_id']=$server_id;
                    $serverDate['member_id']=$remember_id;
                    $ruRes=db('member_serve')->lock(true)->insert($serverDate);
                    if(false === $ruRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,服务卡添加失败'));
                    }
                    $user_integral_num=$wash_protect_num+$serveRes['server_num'];
                    $cardNumRes=db('member_user')->where(['id'=>$remember_id])->update(['wash_protect_num_total'=>$user_integral_num]);
                    if($cardNumRes === false){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,洗护次数添加失败'));
                    }
                }else if($submit_type == 4){
                    $integralDate['update_time']=time();
                    $integralDate['create_time']=time();
                    $integralDate['recharge_type']=2;
                    $integralDate['integral_type']=1;
                    $integralDate['integral_num']=$integral_num;
                    $integralDate['member_id']=$remember_id;
                    $integralRes=db('member_integral')->lock(true)->insert($integralDate);
                    if(false === $integralRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }

                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 删除
     */
    public function del(){
        $id = $this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数有误','data'=>'']);
        }
        $r=db('member_vip')->where(['is_delete'=>0,'id'=>$id])->find();
        if(!$r){
            return json(['code'=>0,'msg'=>'会员信息查询失败']);
        }
        $res=db('member_vip')->where(['id'=>$id])->update(['is_delete'=>0]);
        if(!$res){
            return json(['code'=>0,'msg'=>'操作失败']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);

    }


    /**
     * 获取会员卡列表
     * @return \think\response\Json|void
     */
    public function cardList()
    {
        $where['is_delete'] = 0;
        $where['status'] = 0;
        $r=db('cards')->where($where)->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }

    /**
     * 获取充值卡列表
     * @return \think\response\Json|void
     */
    public function storedList()
    {
        $where['is_delete'] = 0;
        $where['status'] = 0;
        $r=db('cards_stored')->where($where)->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }

    /**
     * 获取充值卡列表
     * @return \think\response\Json|void
     */
    public function serverList()
    {
        $where['is_delete'] = 0;
        $where['status'] = 0;
        $r=db('cards_server')->where($where)->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }

    /**
     * 获取会员卡详情
     * @return \think\response\Json|void
     */
    public function getCardDetail()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }
        $where['id'] = $id;
        $r=db('cards')->where($where)->find();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }

    /**
     * 获取充值卡充值记录
     * @return \think\response\Json|void
     */
    public function getStoredDetail()
    {
        $post = input('post.');
        $member_id = isset($post['member_id']) && $post['member_id'] != '' ? $post['member_id'] : 0;
        $user=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->find();
        if(!$user){
            return json(['code' => 0, 'msg' => '会员信息错误']);
        }
        $where['is_delete'] = 0;
        $where['member_id'] = $member_id;
        $r=db('member_recharge')->where($where)->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }


    /**
     * 获取服务卡记录
     * @return \think\response\Json|void
     */
    public function getServerDetail()
    {
        $post = input('post.');
        $member_id = isset($post['member_id']) && $post['member_id'] != '' ? $post['member_id'] : 0;
        $user=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->find();
        if(!$user){
            return json(['code' => 0, 'msg' => '会员信息错误']);
        }
        $sql="select sd.*,a.server_total,s.title as server_title,s.server_num,s.card_price from crm_member_serve AS sd ";
        $sql.=" left join crm_cards_server as s on s.id=sd.serve_id ";
        $sql.=" LEFT JOIN (SELECT COUNT(id) as server_total,server_card_id FROM crm_member_record WHERE is_delete=0 GROUP BY server_card_id) AS a ON a.server_card_id=sd.id ";
        $sql.=" where 1=1 and sd.is_delete=0 and sd.member_id=".$member_id;
        $sql.=" order by sd.id desc ";
        $list=Db::query($sql);
        foreach ($list as &$v){
            $v['server_status']=$v['card_end_time']>=time()?1:0;
        }
        return json(['code' => 1, 'msg' => '操作成功','data'=>$list]);
    }


    /**
     * 获取充值卡充值记录
     * @return \think\response\Json|void
     */
    public function purchaseHistory()
    {
        $post = input('post.');
        $member_id = isset($post['member_id']) && $post['member_id'] != '' ? $post['member_id'] : 0;
        $user=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->find();
        if(!$user){
            return json(['code' => 0, 'msg' => '会员信息错误']);
        }
        $where['xf.is_delete'] = 0;
        $where['xf.member_id'] = $member_id;
        $list = Db::name('member_record')
            ->alias('xf')
            ->field('xf.*,s.name as server_name')
            ->join('server s','s.id=xf.server_id','left')
            ->where($where)
            ->order('xf.id desc')
            ->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$list]);
    }


    /**
     * 添加
     * @return \think\response\Json|void
     *  zs_question       zs_question_option
     *  zs_question_type
     */
    public function cancellation(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $member_id=isset($post['member_id']) && $post['member_id'] != '' ? $post['member_id'] : 0;
                $rUser=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->find();
                if(!$rUser){
                    return json(array('code' => '0', 'msg' => '人员信息错误'));
                }
                $write_type=isset($post['write_type']) && $post['write_type'] != '' ? $post['write_type'] : 0;
                if($write_type == 0){
                    return json(['code' => 0, 'msg' => '参数错误']);
                }
                //销毁会员卡
                if($write_type == 1){
                    $isVip=db('member_vip')->where(['is_delete'=>0,'member_id'=>$rUser['id'],'card_end_time'=>array('egt',time())])->find();
                    if(!$isVip){
                        return json(array('code' => '0', 'msg' => '用户会员卡信息错误!'));
                    }
                    $rVip=db('member_vip')->where(['id'=>$isVip['id']])->update(['is_delete'=>1]);
                    if(false === $rVip){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }else if($write_type == 2){
                    $write_amount_value=isset($post['write_amount_value']) && $post['write_amount_value'] != '' ? $post['write_amount_value'] : 0;
                    if($write_amount_value<=0){
                        return json(['code' => 0, 'msg' => '金额错误']);
                    }
                    $amountNum=db('member_recharge')->where(['is_delete'=>0,'member_id'=>$member_id])->sum('amount');
                    $xfAmountNum=db('member_record')->where(['is_delete'=>0,'member_id'=>$member_id,'katz_or_amount'=>2])->sum('monetary');
                    if($write_amount_value>($amountNum-$xfAmountNum)){
                        return json(['code' => 0, 'msg' => '账户金额不足，请重试']);
                    }
                    $data['member_id']=$member_id;
                    $data['create_time']=time();
                    $data['update_time']=time();
                    $data['katz_or_amount']=2;
                    $data['monetary']=$write_amount_value;
                    $record=db('member_record')->lock(true)->insert($data);
                    if(false === $record){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }else if($write_type == 3){
                    $write_card_num=isset($post['write_card_num']) && $post['write_card_num'] != '' ? $post['write_card_num'] : 0;
                    if($write_card_num<=0){
                        return json(['code' => 0, 'msg' => '卡次错误']);
                    }
                    if($write_card_num>$rUser['wash_protect_num_total']){
                        return json(['code' => 0, 'msg' => '账户卡次不足，请重试']);
                    }
                    $useCardNum=$rUser['wash_protect_num_total']-$write_card_num;
                    $rCard=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->update(['wash_protect_num_total'=>$useCardNum]);
                    if(false === $rCard){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }else if($write_type == 4){
                    $write_integral_num=isset($post['write_integral_num']) && $post['write_integral_num'] != '' ? $post['write_integral_num'] : 0;
                    if($write_integral_num<=0){
                        return json(['code' => 0, 'msg' => '积分错误']);
                    }
                    $integral_sr=db('member_integral')->where(['member_id'=>$member_id,'integral_type'=>1])->sum('integral_num');
                    $integral_xf=db('member_integral')->where(['member_id'=>$member_id,'integral_type'=>2])->sum('integral_num');
                    if($write_integral_num>($integral_sr-$integral_xf)){
                        return json(['code' => 0, 'msg' => '账户积分不足，请重试']);
                    }
                    $integralDate['update_time']=time();
                    $integralDate['create_time']=time();
                    $integralDate['recharge_type']=1;
                    $integralDate['integral_type']=2;
                    $integralDate['member_id']=$member_id;
                    $integralDate['integral_num']=$write_integral_num;
                    $integralRes=db('member_integral')->lock(true)->insert($integralDate);
                    if(false === $integralRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }
}